var config = require('../../config.json');

var logger = require('log4js').getLogger();
var request = require('request');
var sdp_server = config.sdp_server.host + ":" + config.sdp_server.port;

/**
 * 创建项目：
 * 1. 数据库中添加新建项目数据
 * 2. member中添加数据
 * 3. 为项目创建git库（包括master分支和develop分支，直接使用自己的git服务）
 * 4. 为项目创建master_workspace（clone master分支）
 * 5. 在这个过程中失败的话，提供回滚：删除项目数据，成员数据，git库，master_workspace
 * TODO::如果支持第三方git库，这里创建git库的过程需要变化
 *
 * @param req
 * @param res
 * @param next
 */
exports.addProject = function (req, res, next) {
    var projectInfo = req.body;
    var user = req.session.user.shortid;
    projectInfo['creator'] = user;
    var project = {};
    request.post(sdp_server + "/api/project", {form: projectInfo}, function (err, response, data) {
        var dataJson = JSON.parse(data);
        if (err || dataJson.code == '500') {
            logger.error("创建项目失败");
            logger.error(err);
            return res.format_json(null, 500, "创建项目失败!");
        } else {
            logger.info("项目创建完成");
            res.format_json({success: true, project: dataJson.data.project});
        }
    });
};
exports.deleteProject = function (req, res, next) {
    //删除项目相关内容：project，member，workspace，buildConfigs，builds，productConfig,publishConfig
    var project_id = req.params.project_id;
    var cur_project = req.cookies.cur_project;
    if (cur_project && cur_project._id == project_id) {
        res.clearCookie("cur_project");
    }
    request({
        url: sdp_server + "/api/project/" + project_id,
        method: "DELETE",
        json: true
    }, function (err, response, data) {
        if (err) {
            return res.format_json(null, 500, "删除项目失败:" + err);
        }
        return res.format_json({}, 200);
    });
};

exports.addDependency = function (req, res, next) {
    var dependency_info = req.body;
    var project_id = req.params.project_id;
    request.post(sdp_server + "/api/dependency/" + project_id, {form: dependency_info}, function (err, response, data) {
        var dataJson = JSON.parse(data);
        if (err || dataJson.code == '500') {
            logger.error("添加依赖失败");
            logger.error(err);
            return res.format_json(null, 500, "添加依赖失败!");
        } else {
            res.format_json(dataJson);
        }
    });
};

exports.removeDependency = function (req, res, next) {
    var dependency_info = req.body;
    var project_id = req.params.project_id;
    request(
        {
            url: sdp_server + "/api/dependency/" + project_id,
            method: "DELETE",
            json: true,
            body: dependency_info
        }
        , function (err, response, data) {
            if (err) {
                return res.format_json(null, 500, "删除依赖失败:" + err);
            }
            res.format_json(data.data);
        });
};

exports.updateDependency = function (req, res, next) {
    var dependency_info = req.body;
    var project_id = req.params.project_id;
    request(
        {
            url: sdp_server + "/api/dependency/" + project_id,
            method: "PUT",
            json: true,
            body: dependency_info
        }
        , function (err, response, data) {
            if (err) {
                return res.format_json(null, 500, "更新依赖失败:" + err);
            }
            res.format_json(data);
        });
};

exports.updateDependencies = function (req, res, next) {
    var dependencies = req.body;
    var project_id = req.params.project_id;
    var sdp_server = config.sdp_server.host + ":" + config.sdp_server.port;

    request(
        {
            url: sdp_server + '/api/dependencies/' + project_id,
            method: "PUT",
            json: true,
            body: dependencies
        }
        , function (err, response, data) {
            if (err) {
                return res.format_json(null, 500, "更新依赖失败:" + err);
            }
            res.format_json(data);
        });
};

exports.removeCert = function (req, res, next) {
    var body = req.body;
    request(
        {
            url: sdp_server + '/api/project/removeCert',
            method: "DELETE",
            json: true,
            body: body
        }
        , function (err, response, data) {
            if (err) {
                return res.format_json(null, 500, "更新依赖失败:" + err);
            }
            res.format_json(data);
        });
};

exports.getCurrentProject = function (req, res, next) {
    var cur_project = req.cookies.cur_project;
    var user = req.query.user;
    var url = null;
    if (cur_project != 'undefined' && typeof(cur_project) == "string") {
        url = sdp_server + '/api/project?user=' + user;
    }
    else {
        url = sdp_server + '/api/project?user=' + user + '&cur_project=' + cur_project;
    }

    request(url, function (err, request, data) {
        var dataJson = JSON.parse(data);
        if (err || dataJson.code == 500) {
            return res.format_json(null, 500, err);
        } else {
            res.cookie("cur_project", dataJson.data._id, {maxAge: 36000000});
            res.format_json(dataJson.data, 0);
        }
    })

};